package cn.edu.ctbu.thymeleafwork.webapi;

import cn.edu.ctbu.thymeleafwork.core.PageUtils;
import cn.edu.ctbu.thymeleafwork.domain.Student;
import cn.edu.ctbu.thymeleafwork.service.StudentService;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;



import java.util.List;

@RequestMapping("/webapi/student")
@RestController
@Slf4j
public class StudentRestController {

    @Autowired
    private StudentService studentService;


    /**
     * 读取的url:/webapi/student/list
     * @return
     */
    @GetMapping("/list")
    public List<Student> getAll(){

        List<Student> students=studentService.findAll();

        return students;
    }

    /**
     * 新增学生的方法/webapi/stuednt/insert
     * @param student
     * @return
     */
    /*@PostMapping ("/insert")
    public Student insert(Student student){
        Student student1=studentService.insert(student);
        return student1;
    }*/

    /**
     * 更新学生的方法/webapi/stuednt/update
     * @param student
     * @return
     */
   /* @PutMapping ("/update")
    public Student update(Student student){
        //读取旧的数据
        Student student1=studentService.getById(student.getId());

        if(StringUtils.isEmpty(student.getPassword())){
            //没有新密码，那么就用旧密码
            student.setPassword(student1.getPassword());
        }
        student=studentService.update(student);
        return student;
    }*/

    /**
     * 删除学生的方法/webapi/stuednt/delete
     * @param id
     * @return
     */
    @DeleteMapping  ("/delete/{id}")
    public void delete(@PathVariable Integer id){
        studentService.delete(id);
    }


    /**
     * 读取的url:/webapi/student/get/id
     * @return
     */
    @GetMapping("/get/{id}")
    public Student get(@PathVariable Integer id){

        Student student=studentService.getById(id);
        student.setPassword("");

        return student;
    }

    /**
     * 分页读取全部内容,并可按姓名进行过滤查询
     * @return
     */
    @GetMapping("/getbypage")
    public PageUtils getByPage(@RequestParam(value = "page", defaultValue = "0") Integer page,
                               @RequestParam(value = "size", defaultValue = "10") Integer size,
                               @RequestParam(value = "name", defaultValue = "") String name,
                               @RequestParam(value = "no", defaultValue = "") String no,
                               @RequestParam(value = "sex", defaultValue = "") Integer sex) {

        // 按id排倒序
        Sort sort = Sort.by(Sort.Direction.DESC, "id");

        Page<Student> studentPage;

        if (StringUtils.isEmpty(name) && StringUtils.isEmpty(no) && StringUtils.isEmpty(sex)) {
            // 没有查询参数，返回全部内容
            Pageable pageable = PageRequest.of(page, size, sort);
            studentPage = studentService.findAll(pageable);
        } else {
            // 使用查询参数进行过滤
            Student student = new Student();
            student.setName(name);
            student.setNo(no);
            student.setSex(sex);

            Pageable pageable = PageRequest.of(page, size, sort);

            ExampleMatcher matcher = ExampleMatcher.matching()
                    .withMatcher("name", ExampleMatcher.GenericPropertyMatchers.contains())
                    .withMatcher("no", ExampleMatcher.GenericPropertyMatchers.contains())
                    .withMatcher("sex", ExampleMatcher.GenericPropertyMatchers.exact());

            Example<Student> example = Example.of(student, matcher);

            studentPage = studentService.findAll(example, pageable);
        }

        PageUtils pageUtils = new PageUtils(studentPage.getContent(), studentPage.getTotalElements());
        return pageUtils;
    }


    /**
     * 通过姓名查询
     * @param name
     * @return
     */
    @GetMapping("/search")
    public List<Student> searchStudents(@RequestParam("name") String name) {
        List<Student> students = studentService.findByNameLike(name);
        return students;
    }


    /**
     * 新增学生的方法/webapi/stuednt/insert
     * @param student
     * @return
     */
    @PostMapping(value = "/insert")
    public int insert(@Valid Student student, BindingResult bindingResult){

        if (bindingResult.hasErrors()) {
            log.info(bindingResult.getFieldError().getDefaultMessage());
            return -1;

        }
        studentService.insert(student);
        Integer myid=student.getId();
        return myid.intValue();
    }

    /**
     * 更新学生的方法/webapi/stuednt/update
     * @param student
     * @return
     */
    @PutMapping (value = "/update")
    public int update(@Valid Student student, BindingResult bindingResult){

        if (bindingResult.hasErrors()) {
            log.info(bindingResult.getFieldError().getDefaultMessage());
            return -1;

        }
        //读取旧的数据
        Student student1=studentService.getById(student.getId());

        if(StringUtils.isEmpty(student.getPassword())){
            //没有新密码，那么就用旧密码
            student.setPassword(student1.getPassword());
        }
        student=studentService.update(student);
        Integer myid=student.getId();
        return myid.intValue();
    }

}
